﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services;
using RndMaterialDisposalService.Services.Interface;
using Ganss.Excel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// 资产赔偿电子流
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CapitalCompensateElectronFlowController : ControllerBase
    {
        private ILogger<CapitalCompensateElectronFlowController> logger;
        private readonly string ProcessFullName = "AssetsManagement\\AssetCompensation";
        private ICapitalCompensateReportFormService capitalCompensateReportFormService;
        private IConfiguration configuration;
        private readonly string SaveFormDataUrl = "/api/WorkflowData/ApplicationData";
        private readonly string ProcessFolioUrl = "/api/WorkflowData/ApplicationNumber";

        public CapitalCompensateElectronFlowController(ILogger<CapitalCompensateElectronFlowController> _logger, 
            ICapitalCompensateReportFormService _capitalCompensateReportFormService,
            IConfiguration _configuration
            )
        {
            logger = _logger;
            capitalCompensateReportFormService = _capitalCompensateReportFormService;
            configuration = _configuration;
        }

        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="procInstID">流程实例编号</param>
        /// <param name="applicationNumber"></param>
        /// <returns></returns>
        [HttpGet("GetFormData")]
        public async Task<IActionResult> GetFormData(string? procInstID, string? applicationNumber)
        {
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var result = new FormInfoResp();
            if (!string.IsNullOrWhiteSpace(procInstID))
            {
                var url = $"{CommonServiceHost}{SaveFormDataUrl}?procInstID={procInstID}";
                result = await HttpHelper.GetAsync<FormInfoResp>(url);
                result.ViewsStatus = "Approval";
                return Ok(result);
            }

            var formDataModel = new CapitalCompensateElectronFlowReq();
            var url2 = $"{CommonServiceHost}{ProcessFolioUrl}?workflowCode={ProcessFullName}";
            var appNumber = await HttpHelper.GetAsync<string>(url2);
            result.ApplicationNumber = appNumber;
            result.ViewsStatus = "Start";
            result.FormData = JsonConvert.SerializeObject(formDataModel);
            return Ok(result);
        }

        /// <summary>
        /// 返回资产维修电子流报表主数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("CapitalCompensateReportFormData")]
        [PageList]
        public IActionResult GetCapitalCompensateReportFormData(CapitalCompensateReportConditionModel input)
        {
            var list = capitalCompensateReportFormService.GetCapitalCompensateReportFormPageList(input);
            int count = capitalCompensateReportFormService.GetCapitalCompensateReportFormData(input).Count();

            var result = ApiResponsePageList<CapitalCompensateReportFormModel>.CreatePageListByResult(list, input.pageIndex, input.pageSize, count);

            return Ok(result);
        }

        /// <summary>
        /// 新增报表数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("SavaCapitalCompensateReportFormData")]
        public async Task<IActionResult> SavaCapitalCompensateReportFormData(CapitalCompensateReportDataModel input) 
        {
            int count = 0;
            string _ProcInstId = input.ProcInstId ?? "0";
            try
            {
                if (input != null)
                {
                    CapitalCompensateBusinessDataModel item = new CapitalCompensateBusinessDataModel();
                    item.SysId = Guid.NewGuid().ToString("N");
                    item.ProcessFolio = input.ProcessFolio.Trim() ?? "";
                    item.ProcInstId = input.ProcInstId ?? "";
                    item.Applicant = input.Applicant ?? "";
                    item.ApplicantTime = Convert.ToDateTime(input.ApplicantTime);
                    item.ApplicantName = input.ApplicantName ?? "";
                    item.Telephone = input.Telephone ?? "";
                    item.CompanySegment = input.CompanySegment ?? "";
                    item.LargeSectors = input.LargeSectors ?? "";
                    item.SmallSector = input.SmallSector ?? "";
                    item.DepartmentCode = input.DepartmentCode ?? "";
                    item.DepartmentHead = input.DepartmentHead ?? "";
                    item.DepartmentHeadUserId = input.DepartmentHeadUserId ?? "";
                    item.FirstLevelAssetManager = input.FirstLevelAssetManager ?? "";
                    item.FirstLevelAssetManagerUserID = input.FirstLevelAssetManagerUserID ?? "";
                    item.Share = input.Share ?? "";
                    item.ShareUserId = input.ShareUserId ?? "";
                    item.ShareName = input.ShareName ?? "";
                    item.ReasonsForAssetCompensation = input.ReasonsForAssetCompensation ?? "";
                    item.AssetCompensationDescription = input.AssetCompensationDescription ?? "";
                    item.RelevantCredentials = input.RelevantCredentials ?? "";
                    item.CreateTime = DateTime.Now;

                    List<CapitalCompensateBusinessSubtableDataModel> list = new List<CapitalCompensateBusinessSubtableDataModel>();
                    input.AssetDetail.ForEach((x) => {
                        list.Add(new CapitalCompensateBusinessSubtableDataModel
                        {
                            SysId = Guid.NewGuid().ToString("N"),
                            ProcInstId = input.ProcInstId ?? "",
                            AssetNo = x.AssetNo ?? "",
                            AssetName = x.AssetName ?? "",
                            UserName = x.UseName ?? "",
                            UseCode = x.UseCode ?? "",
                            DeptName = x.DeptName ?? "",
                            DeptCode = x.DeptCode ?? "",
                            StartDate = x.StartDate,
                            QualityStatus = x.QualityStatus.ToString(),
                            OriginalValue = x.OriginalValue.ToString(),
                            AccumulatedDepreciation = x.AccumulatedDepreciation.ToString(),
                            NetWorth = x.NetWorth.ToString(),
                            CompensationAmount = x.CompensationAmount ?? "",
                            CreateTime = DateTime.Now,
                            AssetLoseDate = x.AssetLoseDate,
                        });
                    });

                    count = await capitalCompensateReportFormService.AddCapitalCompensateBusinessData(item, list);
                }
                logger.LogInformation($"新增报表数据（资产赔偿电子流）,流程实例号：{_ProcInstId},数量：{count},时间：{DateTime.Now}");
                return Ok(count);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"新增报表数据（资产赔偿电子流）,流程实例号：{_ProcInstId},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                throw;
            }
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="relativePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet("DownloadFile")]
        [PageList]
        public async Task<IActionResult> DownloadFile(string relativePath, string fileName)
        {
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            var fileFullPath = $"{fileDir}\\{relativePath}";
            var stream = await System.IO.File.ReadAllBytesAsync(fileFullPath);
            return File(stream, "application/octet-stream", fileName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("CapitalCompensateReportExport")]
        [PageList]
        public async Task<IActionResult> CapitalCompensateReportExport(CapitalCompensateReportConditionModel inputCondition)
        {
            inputCondition.pageIndex = 1;
            inputCondition.pageSize = 65535;
            var list = capitalCompensateReportFormService.GetCapitalCompensateReportFormPageList(inputCondition);
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
            {
                Directory.CreateDirectory($"{fileDir}\\Report");
            }
            var filePath = $"Report\\资产赔偿电子流报表{Guid.NewGuid().ToString("N")}.xlsx";
            await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", list);
            return Ok(filePath);
        }
    }
}
